package com.example.message.service;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;

@Service("sysMessageService")
public class SysMessageServiceImpl implements SysMessageService, InitializingBean, DisposableBean {

    @Value("${sitc.file.dir}")
    private String filePath;

    @Resource
    private SysFileMessageListener sysFileMessageListener;

    private FileAlterationObserver fileAlterationObserver;

    private FileAlterationMonitor fileAlterationMonitor;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.initFolder();
        this.startMonitor();
    }

    @Override
    public void destroy() throws Exception {
        this.stopMonitor();
    }

    @Override
    public void initFolder() {
        File serviceDir = new File(this.filePath + SERVICES);
        File jobDir = new File(this.filePath + JOBS);
        File messageDir = new File(this.filePath + MESSAGES);
        if (!serviceDir.exists()) {
            serviceDir.mkdirs();
        }
        if (!jobDir.exists()) {
            jobDir.mkdirs();
        }
        if (!messageDir.exists()) {
            messageDir.mkdirs();
        }
    }

    @Override
    public void startMonitor() throws Exception {
        this.fileAlterationObserver = new FileAlterationObserver(new File(this.filePath + MESSAGES));
        this.fileAlterationObserver.addListener(sysFileMessageListener);
        this.fileAlterationMonitor = new FileAlterationMonitor(TIME);
        this.fileAlterationMonitor.addObserver(fileAlterationObserver);
        this.fileAlterationMonitor.start();
    }

    @Override
    public void stopMonitor() throws Exception {
        this.fileAlterationMonitor.stop();
        this.fileAlterationObserver.destroy();
    }
}
